import styles from "./styles.module.less";
import { useEffect, useRef, useState } from "react";
import { getChat } from "@/utils/front/index";
import { Avatar, Input } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { io } from "socket.io-client";
import send from "@/assets/icons/send.png";
import { addChat } from "@/utils/front/index";
import LoginModal from "@/components/other/Login/index";
import { setLogin } from "@/store/modules/user";
import EmojiPicker from "@/components/other/EmojiPicker";

const ChatRoom = () => {
  // 标题
  const titleArea = () => {
    return (
      <>
        <div className={styles.left}>聊天室</div>
        <div className={styles.right}>
          <span className={styles.point}></span> 在线:{onlineNum}人
        </div>
      </>
    );
  };
  // 消息列表
  const [onlineNum, setOnlineNum] = useState<number>();
  const [chatList, setChatList] = useState<any[]>([]);
  const { userInfo } = useSelector((state: any) => state.user);
  const socketRef = useRef<any>(null);
  const messageListRef = useRef<HTMLDivElement>(null);
  console.log(userInfo);

  const getChatList = () => {
    getChat().then((res: any) => {
      setChatList(res.msg);
    });
  };
  const scrollBottom = () => {
    //滚动到最底部
    if (messageListRef.current) {
      messageListRef.current.scrollIntoView({
        // behavior: "smooth",
        block: "end",
        inline: "nearest",
      });
    }
  };
  useEffect(() => {
    scrollBottom();
  }, [chatList]);
  useEffect(() => {
    socketRef.current = io("http://localhost:3000");
    console.log("调用了socket");
    // 添加事件监听器
    socketRef.current.on("message", (data: any) => {
      console.log("回调", data);
      setChatList((prev: any) => [...prev, data]);
      scrollBottom();
    });
    socketRef.current.on("num", (data: number) => {
      console.log("房间人数", data);
      setOnlineNum(data);
    });
    getChatList();

    // 清理函数：移除事件监听器
    return () => {
      if (socketRef.current) {
        socketRef.current.off("message");
        socketRef.current.off("num");
        socketRef.current.disconnect();
      }
    };
  }, []);

  const contentArea = () => (
    <div className={styles.messageList}>
      {chatList.map((item: any) => {
        const isOwnMessage = userInfo && item.userId == userInfo.id;
        const messageItemClass = isOwnMessage
          ? styles.ownMessageItem
          : styles.otherMessageItem;

        return (
          <div
            className={`${styles.messageItem} ${messageItemClass}`}
            key={item.messageId}
          >
            {/* 根据是否是当前用户的消息决定布局 */}
            {isOwnMessage ? (
              <>
                <div className={styles.messageContent}>
                  <div className={styles.messageInfo}>
                    <span className={styles.messageTime}>{item.time}</span>
                    <span className={styles.messageName}>{item.name}</span>
                  </div>
                  <div className={styles.messageText}>{item.content}</div>
                </div>
                <Avatar src={item.avatar} />
              </>
            ) : (
              <>
                <Avatar src={item.avatar} />
                <div className={styles.messageContent}>
                  <div className={styles.messageInfo}>
                    <span className={styles.messageName}>{item.name}</span>
                    <span className={styles.messageTime}>{item.time}</span>
                  </div>
                  <div className={styles.messageText}>{item.content}</div>
                </div>
              </>
            )}
          </div>
        );
      })}
      <div ref={messageListRef}></div>
    </div>
  );

  // 输入框
  interface Emoji {
    id: number;
    emoji: string;
    label: string;
  }
  const [inpValue, setInpValue] = useState("");
  const [selectedEmoji, setSelectedEmoji] = useState<Emoji | null>(null);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);

  const handleEmojiClick = (emoji: Emoji) => {
    setSelectedEmoji(emoji);
    // 在这里处理点击表情后的逻辑，比如将表情添加到输入框等
    console.log(selectedEmoji);
    setInpValue(inpValue + emoji.emoji);
  };
  const handleMouseEnter = () => {
    setShowEmojiPicker(true);
  };

  const handleMouseLeave = () => {
    setShowEmojiPicker(false);
  };

  const sendMsg = () => {
    console.log("发送消息");
    addChat({ userId: userInfo.id, content: inpValue }).then((res: any) => {
      console.log(res);
      socketRef.current.emit("publish", {
        userId: userInfo.id,
        content: inpValue,
        name: userInfo.name,
        avatar: userInfo.avatar,
        time: "2024-07-29 17:16:10",
      });
      setInpValue("");
    });
  };
  const inputArea = () => {
    return (
      <>
        <div className={styles.input}>
          <div
            className={styles.inputEmoji}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
          >
            {showEmojiPicker && (
              <EmojiPicker
                width={280}
                height={200}
                onEmojiClick={handleEmojiClick}
              />
            )}
            <span style={{ fontSize: "28px" }}>😀</span>
          </div>
          <Input
            placeholder="Basic usage"
            value={inpValue}
            onChange={(e) => {
              setInpValue(e.target.value);
            }}
          />
          <div className={styles.inputIcon} onClick={sendMsg}>
            <img className={styles.img} src={send} alt="Send Icon" />
          </div>
        </div>
      </>
    );
  };

  // 登录模块
  const [modalVisible, setModalVisible] = useState(false);
  const { login } = useSelector((state: any) => state.user);
  const disPatch = useDispatch();
  useEffect(() => {
    if (login) {
      setModalVisible(true);
    }
  }, [login]);
  const handleCancel = () => {
    setModalVisible(false);
    disPatch(setLogin(false));
    console.log("login", login);
  };
  const handleConfirm = () => {
    setModalVisible(false);
  };
  const loginArea = () => {
    return (
      <LoginModal
        visible={modalVisible}
        onCancel={handleCancel}
        onConfirm={handleConfirm}
      />
    );
  };

  return (
    <>
      {loginArea()}
      <div className={styles.chatRoom}>
        <div className={styles.titleArea}>{titleArea()}</div>
        <div className={styles.contentArea}>{contentArea()}</div>
        <div className={styles.inputArea}>{inputArea()}</div>
      </div>
    </>
  );
};

export default ChatRoom;
